package lyh.hnu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import lyh.hnu.common.R;
import lyh.hnu.entity.po.Employee;
import lyh.hnu.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        return employeeService.login(request, employee);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        return employeeService.logout(request);
    }

    @PostMapping
    public R<String> saveEmp(HttpServletRequest request, @RequestBody Employee employee) {
        return employeeService.saveEmp(request, employee);
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("分页请求，参数：{},{},{}", page, pageSize, name);
        //分页构造器
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        Page<Employee> p = employeeService.page(pageInfo, queryWrapper);
        //执行查询
        return R.success(p);
    }

    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        if (employee.getId() == 1 && employee.getStatus() == 0) {
            return R.error("无法禁用管理员");
        }
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> selectById(@PathVariable long id) {
        Employee emp = employeeService.getById(id);
        if (emp == null) {
            return R.error("未查询到该员工信息");
        }
        return R.success(employeeService.getById(id));
    }
}
